package arithmetic;

import lombok.extern.slf4j.Slf4j;

/**
 * 链表翻转
 *      输入：1 -> 2 -> 4->7->3
 *      输出：3->7->4->2->1
 * 方法：
 *      1.迭代
 *      2.递归
 */
@Slf4j
public class ListNode {

    private int value;

    private ListNode next;

    public ListNode(int value, ListNode next){
        this.value = value;
        this.next = next;
    }


    public int getValue() {
        return value;
    }

    public ListNode getNext() {
        return next;
    }

    public static void main(String[] args) {
        //构造数据
        ListNode l5 = new ListNode(5,null);
        ListNode l4 = new ListNode(4,l5);
        ListNode l3 = new ListNode(3,l4);
        ListNode l2 = new ListNode(2,l3);
        ListNode l1 = new ListNode(1,l2);
        //调用方法
        ListNode newNode = recursion(l1);
        System.out.println(newNode);
    }

    //通过迭代方式 实现链表翻转
    private static ListNode revert(ListNode l1) {
        ListNode pre = null,next;
        ListNode current = l1;
        while (current!=null){
            next = current.next;
            current.next = pre;
            pre = current;
            current = next;
        }
        return pre;
    }

    /**
     * 通过递归方式实现单链表翻转
     */
    private static ListNode recursion(ListNode currentNode){
        if(currentNode == null || currentNode.next == null){
            log.info("当前节点为：{}",currentNode.getValue());
            return currentNode;
        }
        //递归找到最后一个节点
        ListNode newHead = recursion(currentNode.next);
        log.info("newHead节点为：{}",newHead.getValue());
        while (newHead.next!=null){
            //log.info("newHead子节点：{}",);
        }
        log.info("currentNode节点为：{}",currentNode.getValue());
        currentNode.next.next = currentNode;
        currentNode.next = null;

        return newHead;

    }
}
